package com.newgoldcurrency.activities;

import android.content.Intent;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.view.animation.AnimationUtils;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.anythink.core.api.ATAdInfo;
import com.anythink.core.api.AdError;
import com.anythink.network.mintegral.MintegralATRequestInfo;
import com.anythink.splashad.api.ATSplashAd;
import com.anythink.splashad.api.ATSplashAdListener;
import com.anythink.splashad.api.IATSplashEyeAd;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.activities.main.MainActivity;
import com.newgoldcurrency.bean.UserBean;
import com.newgoldcurrency.databinding.ActivitySplashBinding;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SplashActivity extends AppCompatActivity {
    private ActivitySplashBinding binding;
    private ATSplashAd splashAd;
    private final List<Call> calls=new ArrayList<>();
    private String startActivity="login";
    private boolean adFinish=false,dataFinish =false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivitySplashBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.splashLogo.startAnimation(AnimationUtils.loadAnimation(this, R.anim.scale));
        start();
    }
    private void start() {
        initOpen();
        if(Tools.isReal()){
            loadAdAndData();
        }else{
            Tools.toast("Your device is not real machine.");
        }
    }
    private void loadAdAndData() {
        Tools.log("开始加载广告");
        String token = App.sp.getString("token", "");
        if (App.sp.getBoolean("hasOpen",false)){
            Tools.log("本地用了开屏，开始加载广告");
            loadOpenAds();
        }else {
            Tools.log("本地没用开屏");
            adFinish=true;
        }
        if(token.equals("")){
            Tools.log("结果是要登录，不需要加载数据");
            startActivity="login";
            dataFinish=true;
            if (adFinish){
                Tools.log("数据和广告都完成");
                startActivity(new Intent(this,LoginActivity.class));
                finish();
            }

        }else {
            Tools.log("结果是要去主界面，开始加载数据");
            startActivity="main";
            App.userBean=new Gson().fromJson(JsonParser.parseString(new String(Base64.decode(token.split("\\.")[1], 0))).getAsJsonObject().get("user").getAsString(), UserBean.class);
            HashMap<String, String> map2=new HashMap<>();
            map2.put("token", token);
            Network.post(map2,"homepage/getHasGift", call2 -> {
                call2.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) {
                        runOnUiThread(() -> {
                            try {
                                String jo= Objects.requireNonNull(response.body()).string();
                                App.hasGift = JsonParser.parseString(jo).getAsJsonObject().get("data").getAsJsonObject().get("hasGift").getAsBoolean();
                            } catch (IOException e) {
                                e.printStackTrace();
                                App.hasGift=false;
                            }finally {
                                dataFinish =true;
                                if (adFinish){
                                    Tools.log("数据完成，广告先就完成了");
                                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                                    SplashActivity.this.finish();
                                }else {
                                    Tools.log("数据完成，广告没完成，等待ing");
                                }
                            }
                        });
                    }
                });
                calls.add(call2);
            });
        }
    }
    private void initOpen() {
        MintegralATRequestInfo atMediationRequestInfo = new MintegralATRequestInfo("161003", "f5627f053b53c33399026ef09e45dff7", "420725", "1752745");
        atMediationRequestInfo.setAdSourceId("1499262");
        splashAd = new ATSplashAd(this, "b620dbae8a7ea9",atMediationRequestInfo, new ATSplashAdListener() {
            @Override
            public void onAdLoaded(boolean timeout) {
                Tools.log("onAdLoaded: ");
                if (binding!=null){
                    splashAd.show(SplashActivity.this,binding.splashContainer);
                }
            }
            @Override
            public void onAdLoadTimeout() {
                Tools.log("onAdLoadTimeout: ");
            }
            @Override
            public void onNoAdError(AdError adError) {
                Tools.log("onNoAdError: "+adError);
                onAdFinish(5);
            }
            @Override
            public void onAdShow(ATAdInfo atAdInfo){
                binding.splashLogo.setVisibility(View.GONE);
            }
            @Override
            public void onAdClick(ATAdInfo atAdInfo){
                Tools.log("onAdClick");
            }
            @Override
            public void onAdDismiss(ATAdInfo atAdInfo, IATSplashEyeAd iatSplashEyeAd) {
                onAdFinish(1);
            }
        });
    }
    private void onAdFinish(int i) {
        adFinish=true;
        Tools.log("onAdFinish: "+i);
        if (dataFinish){
            Tools.log("广告完成，数据先就完成了");
            if (startActivity.equals("login")){
                startActivity(new Intent(SplashActivity.this,LoginActivity.class));
            }else {
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
            }
            finish();
        }else {
            Tools.log("广告完成，数据没完成，等待ing");
        }
    }
    private void loadOpenAds(){
        if (splashAd.isAdReady()){
            splashAd.show(this, binding.splashContainer);
        }else{
            splashAd.loadAd();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Call call:calls)call.cancel();
        binding=null;
    }
}